<template>
  <div class="h100 stereotyList">
    <!-- 搜索区域 -->
    <div class="tableListSearch">
      <stereotype-search
        @query="handleSearch"
        @clear="clearCondition"
        @handleAddEdit="handleAddEdit"
        @handleBatchDelete="handleBatchDelete" @handleImport="handleImport"
        @exportXlsx="exportXlsx"
        :exporting="exporting"
        ref="searchRef"></stereotype-search>
    </div>
    <!-- 操作区域 -->
    <!-- <div class="searchBtns" style="margin-top: 8px;"> -->
      <!-- <a-button-group>
        <auth-button type="primary" @click="handleSearch(true)" :auth="managePerms.modelStyle.view">
          <i class="iconfont icon-chazhao"></i>
          {{ $t('inquiry') }}
        </auth-button>
        <a-button @click="clearCondition">
          <i class="iconfont icon-qingkong"></i>
          {{ $t('clear') }}
        </a-button>
      </a-button-group>
      <auth-button @click="handleAddEdit" :auth="managePerms.modelStyle.add">
        <i class="iconfont icon-xinjian"></i>
        {{ $t('new') }}
      </auth-button>
      <auth-button type="danger" :auth="managePerms.modelStyle.delete" @click="handleBatchDelete">
        <i class="iconfont icon-shanchu"></i>
        {{ $t('batchDelete') }}
      </auth-button>
      <auth-button @click="importVisible=true" :auth="managePerms.modelStyle.import">
        {{ $t('import') }}
      </auth-button>
      <auth-button @click="exportXlsx" :loading="exporting" :auth="managePerms.modelStyle.export">
        {{ $t('export') }}
      </auth-button> -->
      <!-- <auth-button @click="syncCloudCertVin" :loading="syncloading">
        数据更新
      </auth-button> -->
    <!-- </div> -->
    <!-- 列表区域 -->
    <div class="tableListMain commonTableSty">
      <stereotype-table-list 
      ref="flowConfigTableComp" 
      @handleCopy="handleCopy" 
      @handleEdit="handleEdit"
      @selectedRowchange="handleselectedRowchange"
      @tableReload="tableReload"
      ></stereotype-table-list>
    </div>

    <!-- 导入模块 -->
    <a-modal
      v-model="importVisible"
      title="导入款型"
      width="1000px"
      dialogClass="createFormStyle"
      :bodyStyle="{ height: '500px', overflowY: 'auto' }"
    >
      <template slot="footer">
        <a-button @click="importVisible = false" type="primary">{{ $t('back') }}</a-button>
      </template>
      <div>
        <a-input
          class="formFileInput"
          :placeholder="$t('formatFiles')"
          readOnly
          :value="importFile"
          style="width:400px;margin-right: 10px"
        >
          <template #addonAfter>
            <i class="iconfont icon-shangchuan" @click="$refs.upload.uploadDo()"></i>
          </template>
        </a-input>
        <a-button @click="downloadTemplate" :loading="downloading">{{ $t('downloadTemplate') }}</a-button>
        <a-spin :spinning="importing" tip="导入中...">
          <div style="min-height: 300px">
            <template v-if="uploadRes.fail.length > 0">
              <h4 style="margin-top:20px;color:red">失败明细(共{{uploadRes.failCount}}条)：</h4>
              <a-table
                ref="importFailTable"
                class="h100 withMinHeightTbodyBox"
                :rowKey="(record, index) => 'fail-' + index"
                :columns="importFailColumns"
                :data-source="uploadRes.fail"
                :scroll="{x:1350,y:350}"
                :pagination="false"
              >
                <span
                  slot="message"
                  slot-scope="message"
                  style="color:red;white-space: pre-line"
                >{{ message }}</span>
              </a-table>
            </template>
            <template v-if="uploadRes.success.length > 0">
            <h4 style="margin-top:20px;">导入成功(共{{uploadRes.successCount}}条)：</h4>
            <a-table
              v-if="uploadRes.success.length > 0"
              ref="importSuccessTable"
              class="h100 withMinHeightTbodyBox"
              :rowKey="(record, index) => 'suc-' + index"
              :columns="importSuccessColumns"
              :data-source="uploadRes.success"
              :scroll="{x:1350,y:350}"
              :pagination="false"
            ></a-table>
          </template>
          </div>
        </a-spin>
        <!-- 来自文件上传 -->
        <local-upload
          ref="upload"
          :domView="false"
          @showFileObj="showFileObj"
          :accept="['.xls','.xlsx']"
        ></local-upload>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { managePerms } from '@/config/permission/index'
import {downloadBlobFile} from '@/utils/functions'
import LocalUpload from '@/components/Upload/LocalUpload'
import StereotypeTableList from './components/StereotypeTableList.vue'
import StereotypeSearch from './components/StereotypeSearch.vue'
import AuthButton from '@/components/AuthButton'
import EditModelStyle from './components/EditModelStyle.vue'
import { minxinDrawerUse } from '@/utils/mixin'
import { stereotypeTbColumns } from './config/list'
import moment from 'moment'
import vehicleApi from '@/api/modules/system/vehicleMana'

export default {
  mixins: [minxinDrawerUse],
  components: {
    StereotypeTableList,
    StereotypeSearch,
    AuthButton,
    EditModelStyle,
    LocalUpload
  },
  data () {
    let data = {
      managePerms,
      queryParam:{},
      exporting: false,
      syncloading: false,
      importVisible:false,
      importFile: '',
      uploadRes: {
        fail: [],
        success: [],
        failCount: 0,
        successCount: 0
      },
      downloading: false,
      importing: false,
      //选中行数据
      selectedRows: [],
      selectedIdArr: [],
      columns:stereotypeTbColumns
    }
    let cols = [
      {
        title: '车型代码',
        dataIndex: 'modelCode',
        key: 'modelCode',
        width: 150
      },
      ...data.columns,
    ]
    cols.splice(cols.length - 6, 6)
    cols.splice(1, 4)
    cols.push(
      {
        title: '失败原因',
        dataIndex: 'message',
        width: 200,
        fixed: 'right',
        scopedSlots: { customRender: 'message' }
      }
    )
    data.importFailColumns = cols
    data.importSuccessColumns = [...cols]
    data.importSuccessColumns.splice(cols.length - 1, 1)
    return data
  },
  watch:{
    importVisible(val) {
      if (!val) {
        this.importFile = ''
        this.uploadRes.fail = []
        this.uploadRes.success = []
      }
    }
  },
  methods: {
    // 清空重置按钮点击
    clearCondition() {
      this.$store.commit('resetModelStyleQueryParams')
      this.$refs.searchRef.createTime=null
      this.handleSearch()
    },
    // 顶部搜索区域点击查询按钮
    handleSearch(){
      this.queryParam=this.$refs.searchRef.queryParam
      this.$refs.flowConfigTableComp.refreshData(true)
    },
    handleCopy(val){
      this.handleAddEdit('',val)
    },
    handleEdit(val){
      this.handleAddEdit(val)
    },
    handleImport () {
      this.importVisible = true
    },
    saveData (data) {
      if (data.id) {
        return this.$api.editModelStyle(data)
      }
      return this.$api.addModelStyle(data);
    },
    // 新建/编辑车辆
    handleAddEdit (vehicleId, copyId = '') {
      const _this = this
      const buttons = this.getRightDrawerFooterButtons({
        // key: vehicleId ? managePerms.vehicle2.edit : managePerms.vehicle2.add,
        method: 'saveData',
        callback () {
          _this.$refs.flowConfigTableComp.refreshData(true)
        }
      })
      const vars = { nowTime: Date.now(), vehicleId, copyId}
      if (!copyId && !vehicleId) {
        this.showRightDrawerNoReset(EditModelStyle, this.$t(vehicleId ? 'edit' : 'new') , buttons, 'large', vars);
      } else {
        this.showRightDrawer(EditModelStyle, this.$t(vehicleId ? 'edit' : 'new') , buttons, 'large', vars);
      }
    },
    // 点击批量删除按钮
    handleBatchDelete () {
      if (this.selectedRows.length === 0) {
        this.$message.error("请选择要删除的数据！");
        return
      }
      if (this.selectedRows.length > 0) {
        const selectedApplyNums = this.selectedRows.map((item) => {
          return '"' + item.productionSeries + '-' + item.productionModel + '"'
        })
        const that = this
        this.$confirm({
          title: that.$t('systemTip'),
          content: that.$t('删除后无法恢复，确定要删除 __Content__ 吗？').replace('__Content__', selectedApplyNums.toString()),
          onOk () {
            that.$api.deleteModelStyle({ ids: that.selectedIdArr }).then(() => {
              that.$message.success(that.$t('successfullyDelete'))
              that.$refs.flowConfigTableComp.refreshData(true)
            })
          }
        })
      } else {
        this.disableBatchDeleteBtn = true
      }
    },
    tableReload(){
      this.selectedRows=[]
      this.selectedIdArr=[]
    },
    // 表格组件选择项改变后传递上来触发的事件
    handleselectedRowchange (data) {
      if (data.length > 0) {
        this.disableBatchDeleteBtn = false
        this.selectedIdArr = data.map((item) => {
          return item.id
        })
      } else {
        this.disableBatchDeleteBtn = true
      }
      this.selectedRows = data
    },
    exportXlsx(){
      this.exporting = true
      this.$api
        .exportModelStyleList(this.queryParam)
        .then(res => {
          downloadBlobFile(res, '导出款型' + moment().format('YYYYMMDDHHmmss') + '.xlsx')
        })
        .finally(() => {
          this.exporting = false
        })
    },
    syncCloudCertVin() {
      const vm = this
      this.$confirm({
        title: '同步车辆',
        content: '是否要开始同步车辆',
        class: 'confirmStyle',
        width: 378,
        onOk () {
          vm.syncloading = true
          vehicleApi.syncCloudCertVin().then(() => {
            vm.$message.success('同步成功!')
            vm.$refs.flowConfigTableComp.refreshData(true) // 刷新页面
          }).finally(()=>{
            vm.syncloading = false
          })
        },
        onCancel () { }
      })
    },
    downloadTemplate() {
      this.downloading = true
      this.$api
        .importModelStyleTemplate()
        .then(res => {
          downloadBlobFile(res, '款型导入模板.xlsx')
        })
        .finally(() => {
          this.downloading = false
        })
    },
    showFileObj(value) {
      const vm = this
      vm.importFile = value.name
      const formData = new FormData()
      formData.append('file', value)
      this.uploadRes.fail = []
      this.uploadRes.success = []
      this.uploadRes.failCount = 0
      this.uploadRes.successCount = 0
      this.importing = true;
      vm.$api
        .importModelStyleList(formData)
        .then(res => {
          if (res.data) {
            if (res.data.fail) {
              res.data.fail.forEach(item => {
                vm.uploadRes.fail.push({
                  ...item.data,
                  message: item.message
                })
              })
              vm.uploadRes.failCount = vm.uploadRes.fail.length
              // 截取500条
              vm.uploadRes.fail.splice(500)
            }
            if (res.data.success) {
              res.data.success.forEach(item => {
                vm.uploadRes.success.push(item.data)
              })
              vm.uploadRes.successCount = vm.uploadRes.success.length
              vm.uploadRes.success.splice(500)
            }
            if (vm.uploadRes.successCount === 0 && vm.uploadRes.failCount === 0) {
              vm.$message.error('没有数据！')
            }
            if (vm.uploadRes.successCount > 0) {
              this.$refs.flowConfigTableComp.refreshData(false)
            }
          }
        })
        .catch(() => {
          vm.importFile = ''
        }).finally(() => this.importing=false)
    },

  }
}
</script>
<style scoped lang="less">
.stereotyList{
  padding: 24px 24px 0 24px;
  height: 100%;
}
.tableListAction {
  margin-top: 16px;
  button {
    margin-right: 16px;
    &:nth-last-child(1) {
      margin-right: 0;
    }
  }
}
.tableListMain {
    margin-top: 16px;
    margin-bottom: 16px;
    height: calc(100% - 160px);
  }
</style>
